package com.example.springboot.utils;
import com.example.springboot.domain.Admin;
import com.example.springboot.dto.AdminDTO;
import com.example.springboot.dto.AdminDTO2;
import com.example.springboot.exception.NotLoginException;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.time.Instant;
import java.util.Date;

/**
 * tokenTool
 * @author leopard
 *
 */
public class JwtUtil {

    static String secret = "ddddd";


    public static String createToken(Admin admin) {
        Date exp = Date.from(Instant.ofEpochMilli(System.currentTimeMillis() + 100000));
        long l = System.currentTimeMillis() + 1000 * 60 * 60;
        Date date = new Date(l);
        SecretKey key = new SecretKeySpec(secret.getBytes(), "AES");

        return Jwts.builder()
                .claim("username", admin.getUsername())
                .claim("nickName", admin.getNickName())
                .claim("role",admin.getRoleId())
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256, key)
                .compact();
    }


    @Deprecated
    public static boolean isExpiration(String token){
        return getTokenBody(token).getExpiration().before(new Date());
    }

    public static Claims getTokenBody(String token) {
        SecretKey key = new SecretKeySpec(secret.getBytes(), "AES");
        Claims claims=null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();

        }
        catch (ExpiredJwtException e){
             claims = e.getClaims();

        }
        catch (Exception e) {
            e.printStackTrace();
            throw new NotLoginException(5002,"用户登录信息过期");
        }
        return claims;
    }

    public static Admin getAdmin(String token) {
        Claims claims=null;
        Admin admin=new Admin();
        claims=getTokenBody(token);
        admin.setUsername(claims.get("username").toString());
        admin.setNickName(claims.get("nickName").toString());
        admin.setRoleId(Integer.parseInt( claims.get("role").toString()));
        return admin;
    }

}